<template>
  <div class="app-container">
    <div class="circle-header">
      <div class="circle-info">
        <div class="circle-avatar">
          <image-preview :src="circleInfo.circleAvatar" :width="100" :height="100"/>
        </div>
        <div class="circle-details">
          <h2>{{ circleInfo.circleName }}</h2>
          <div>
            <span class="label-text">圈子描述：</span>
            <div class="circle-description">{{ circleInfo.circleDescription }}</div>
          </div>
          <div v-if="tagList.length > 0" class="tag-container">
            <span class="label-text">圈子标签：</span>
            <div class="circle-tags">
              <el-tag v-for="tag in tagList" :key="tag.id" class="tag-item">{{ tag.tagName }}</el-tag>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>成员列表</span>
          <div>
            <el-button 
              type="primary" 
              @click="openAddMemberDialog" 
              v-if="(currentUserRole === 2 || currentUserRole === 3) && !showBlacklist"
              v-hasPermi="['circle:member:add']">
              添加成员
            </el-button>
            <el-button 
              type="warning" 
              @click="switchToBlacklist" 
              v-if="currentUserRole === 2 || currentUserRole === 3"
              v-hasPermi="['circle:member:edit']">
              {{ showBlacklist ? '查看成员' : '查看黑名单' }}
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 成员列表 -->
      <el-table v-loading="loading" :data="memberList" v-if="!showBlacklist">
        <el-table-column label="用户ID" align="center" prop="userId" />
        <el-table-column label="用户昵称" align="center" prop="nickName" />
        <el-table-column label="成员角色" align="center" prop="memberRole">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.memberRole === 3">圈主</el-tag>
            <el-tag type="warning" v-else-if="scope.row.memberRole === 2">管理员</el-tag>
            <el-tag type="info" v-else>会员</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="用户等级" align="center" prop="userLevel">
          <template #default="scope">
            <el-tag type="primary" v-if="scope.row.userLevel">{{ scope.row.userLevel }}</el-tag>
            <span v-else>未知等级</span>
          </template>
        </el-table-column>
        <el-table-column label="加入时间" align="center" prop="joinedTime" width="180" />
        <el-table-column label="成员状态" align="center" prop="memberStatus">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.memberStatus === 1">正常</el-tag>
            <el-tag type="danger" v-else>已退出</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <template v-if="currentUserRole === 2"> 
              <el-button 
                link 
                type="primary" 
                icon="Delete" 
                @click="handleRemoveMember(scope.row)" 
                v-hasPermi="['circle:member:remove']"
              >移除</el-button>
              <el-button 
                link 
                type="primary" 
                icon="Edit" 
                @click="handleUpdateRole(scope.row)" 
                v-hasPermi="['circle:member:edit']"
              >修改角色</el-button>
              <el-button 
                link 
                type="danger" 
                icon="CircleClose" 
                @click="handleAddToBlacklist(scope.row)" 
                v-hasPermi="['circle:member:edit']"
                v-if="scope.row.userId !== userId"
              >加入黑名单</el-button>
            </template>
            
            <template v-else-if="currentUserRole === 3"> 
              <template v-if="scope.row.memberRole !== 2"> 
                <el-button 
                  link 
                  type="primary" 
                  icon="Delete" 
                  @click="handleRemoveMember(scope.row)" 
                  v-hasPermi="['circle:member:remove']"
                  v-if="scope.row.userId !== userId" 
                >移除</el-button>
                <el-button 
                  link 
                  type="primary" 
                  icon="Edit" 
                  @click="handleUpdateRole(scope.row)" 
                  v-hasPermi="['circle:member:edit']"
                  v-if="scope.row.userId !== userId" 
                >修改角色</el-button>
                <el-button 
                  link 
                  type="danger" 
                  icon="CircleClose" 
                  @click="handleAddToBlacklist(scope.row)" 
                  v-hasPermi="['circle:member:edit']"
                  v-if="scope.row.userId !== userId"
                >加入黑名单</el-button>
              </template>
            </template>

            <template v-else-if="currentUserRole === 1 && scope.row.userId === userId"> 
              <el-button 
                link 
                type="primary" 
                icon="Delete" 
                @click="handleSelfExit(scope.row)" 
                v-hasPermi="['circle:member:remove']"
              >退出圈子</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 黑名单列表 -->
      <el-table v-loading="blacklistLoading" :data="blacklistMembers" v-if="showBlacklist">
        <el-table-column label="用户ID" align="center" prop="userId" />
        <el-table-column label="用户昵称" align="center" prop="nickName" />
        <el-table-column label="加入黑名单时间" align="center" prop="joinedTime" width="180" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button 
              link 
              type="primary" 
              icon="Check" 
              @click="handleRemoveFromBlacklist(scope.row)" 
              v-hasPermi="['circle:member:edit']"
            >移出黑名单</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加成员对话框 -->
    <el-dialog :title="'添加成员'" v-model="open" width="500px" append-to-body>
      <el-form ref="memberRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="成员角色" prop="memberRole">
          <el-select v-model="form.memberRole" placeholder="请选择成员角色">
            <el-option label="会员" :value="1" />
            <el-option label="圈主" :value="3" v-if="currentUserRole === 2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改角色对话框 -->
    <el-dialog :title="'修改成员角色'" v-model="roleOpen" width="500px" append-to-body>
      <el-form ref="roleRef" :model="roleForm" :rules="roleRules" label-width="80px">
        <el-form-item label="成员角色" prop="memberRole">
          <el-select v-model="roleForm.memberRole" placeholder="请选择成员角色">
            <el-option label="会员" :value="1" />
            <el-option label="圈主" :value="3" v-if="currentUserRole === 2 || currentUserRole === 3" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitRoleForm">确 定</el-button>
          <el-button @click="cancelRole">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 加入黑名单确认对话框 -->
    <el-dialog :title="'加入黑名单'" v-model="blacklistOpen" width="500px" append-to-body>
      <div>确认将该用户加入黑名单吗？加入黑名单后，该用户将被移出圈子，且无法再次加入。</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAddToBlacklist">确 定</el-button>
          <el-button @click="cancelBlacklist">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CircleDetail">
import { ref, reactive, toRefs, onMounted,getCurrentInstance } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getCircle } from "@/api/circle/circle";
import { 
  listCircleMember, 
  addCircleMember, 
  updateCircleMemberRole, 
  removeCircleMember, 
  getCurrentUserRole,
  addToBlacklist,
  removeFromBlacklist,
  listBlacklist
} from "@/api/circle/member";
import { listTag } from "@/api/tag/tag";
import ImagePreview from "@/components/ImagePreview";
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();

// 圈子ID
const circleId = ref(parseInt(route.params.id));

// 圈子基本信息
const circleInfo = ref({});

// 标签列表
const tagList = ref([]);

// 当前用户ID和角色
const userId = ref(null);
const currentUserRole = ref(null);

// 成员列表相关
const loading = ref(true);
const memberList = ref([]);
const total = ref(0);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  circleId: circleId.value
});

// 黑名单相关
const showBlacklist = ref(false);
const blacklistLoading = ref(false);
const blacklistMembers = ref([]);
const blacklistOpen = ref(false);
const blacklistForm = ref({
  circleId: circleId.value,
  userId: null
});

// 添加成员对话框
const open = ref(false);
const form = ref({
  circleId: circleId.value,
  userId: null,
  memberRole: 1
});
const rules = ref({
  userId: [
    { required: true, message: "用户ID不能为空", trigger: "blur" },
    { 
      validator: (rule, value, callback) => {
        if (value === null || value === undefined || value === '') {
          callback()
        } else if (isNaN(Number(value))) {
          callback(new Error('请输入数字'))
        } else {
         callback()
        }
      }, 
      trigger: "blur" 
    }
  ],
  memberRole: [
    { required: true, message: "成员角色不能为空", trigger: "change" }
  ]
});

// 修改角色对话框
const roleOpen = ref(false);
const roleForm = ref({
  id: null,
  memberRole: 1
});
const roleRules = ref({
  memberRole: [
    { required: true, message: "成员角色不能为空", trigger: "change" }
  ]
});

/** 获取圈子基本信息 */
function getCircleInfo() {
  getCircle(circleId.value).then(response => {
    circleInfo.value = response.data;
    if (circleInfo.value.tagList) {
      tagList.value = circleInfo.value.tagList;
    } else {
      tagList.value = [];
    }
  });
}

/** 获取当前用户在圈子中的角色 */
function fetchCurrentUserRole() {
  const userStore = useUserStore();
  userId.value = userStore.userId || userStore.user?.userId;
  getCurrentUserRole(circleId.value).then(response => {
    currentUserRole.value = response.data;
  });
}

/** 获取成员列表 */
function getList() {
  loading.value = true;
  listCircleMember(queryParams.value).then(response => {
    memberList.value = response.rows.filter(member => member.memberStatus === 1);
    total.value = memberList.value.length; 
    loading.value = false;
  });
}

/** 打开添加成员对话框 */
function openAddMemberDialog() {
  form.value = {
    circleId: circleId.value,
    userId: null,
    memberRole: 1
  };
  open.value = true;
}

/** 取消添加成员 */
function cancel() {
  open.value = false;
}

/** 提交添加成员 */
function submitForm() {
  proxy.$refs["memberRef"].validate(valid => {
    if (valid) {
      addCircleMember(form.value).then(response => {
        proxy.$modal.msgSuccess("添加成功");
        open.value = false;
        getList(); 
        getCircleInfo(); 
      });
    }
  });
}

/** 处理移除成员 */
function handleRemoveMember(row) {
  proxy.$modal.confirm('确认要移除该成员吗？').then(function() {
    return removeCircleMember(row);
  }).then(() => {
    getList();
    getCircleInfo(); 
    proxy.$modal.msgSuccess("移除成功");
  }).catch(() => {});
}

/** 打开修改角色对话框 */
function handleUpdateRole(row) {
  roleForm.value = {
    id: row.id,
    circleId: row.circleId,
    userId: row.userId,
    memberRole: row.memberRole
  };
  roleOpen.value = true;
}

/** 取消修改角色 */
function cancelRole() {
  roleOpen.value = false;
}

/** 提交修改角色 */
function submitRoleForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
      updateCircleMemberRole(roleForm.value).then(response => {
        proxy.$modal.msgSuccess("修改成功");
        roleOpen.value = false;
        getList();
        getCircleInfo(); 
      });
    }
  });
}

/** 会员自己退出圈子 */
function handleSelfExit(row) {
  proxy.$modal.confirm('确认要退出该圈子吗？').then(function() {
    return removeCircleMember(row);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("退出成功");
    router.push('/circle/index');
  }).catch(() => {});
}

onMounted(() => {
  getCircleInfo();
  getList();
  fetchCurrentUserRole();
});


/** 切换显示黑名单/成员列表 */
function switchToBlacklist() {
  showBlacklist.value = !showBlacklist.value;
  if (showBlacklist.value) {
    getBlacklist();
  } else {
    getList();
  }
}

/** 获取黑名单列表 */
function getBlacklist() {
  blacklistLoading.value = true;
  listBlacklist(queryParams.value).then(response => {
    blacklistMembers.value = response.rows;
    total.value = response.total;
    blacklistLoading.value = false;
  });
}

/** 打开加入黑名单对话框 */
function handleAddToBlacklist(row) {
  blacklistForm.value = {
    circleId: row.circleId,
    userId: row.userId
  };
  blacklistOpen.value = true;
}

/** 取消加入黑名单 */
function cancelBlacklist() {
  blacklistOpen.value = false;
}

/** 提交加入黑名单 */
function submitAddToBlacklist() {
  addToBlacklist(blacklistForm.value).then(response => {
    proxy.$modal.msgSuccess("已将用户加入黑名单");
    blacklistOpen.value = false;
    getList();
  });
}

/** 从黑名单移除 */
function handleRemoveFromBlacklist(row) {
  proxy.$modal.confirm('确认要将该用户从黑名单中移除吗？').then(function() {
    return removeFromBlacklist({
      circleId: row.circleId,
      userId: row.userId
    });
  }).then(() => {
    getBlacklist();
    proxy.$modal.msgSuccess("已将用户从黑名单移除");
  }).catch(() => {});
}
</script>

<style scoped>
.circle-header {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.circle-info {
  display: flex;
  align-items: flex-start;
}

.circle-avatar {
  margin-right: 20px;
}

.circle-details {
  flex: 1;
}

.label-text {
  font-weight: bold;
  margin-right: 5px;
  display: inline-block;
}

.tag-container {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.circle-description {
  margin: 10px 0;
  color: #606266;
  line-height: 1.5;
}

.circle-tags {
  display: inline-flex;
  flex-wrap: wrap;
}

.tag-item {
  margin-right: 5px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>